import * as qiniu from 'qiniu-js'
import constants from '@/constants'

/**
 * 获取上传头像凭证
 * @param file 图片
 * @param successCallback 成功回调
 * @param errorCallback 失败回调
 */
export const obtainUploadTokenHeadImage = (file, successCallback = null, errorCallback = null) => {

}

/**
 * 获取上传商品图片凭证
 * @param file 图片
 * @param successCallback 成功回调
 * @param errorCallback 失败回调
 */
export const obtainUploadTokenGoodImage = (file, successCallback = null, errorCallback = null) => {

}

/**
 * 上传图片
 * @param file 图片文件
 * @param token 上传凭证
 * @param next 进度回调
 * @param successCallback 成功回调
 * @param errorCallback 失败回调
 * @return observable
 */
export const uploadFile = (file, token, next = null, successCallback = null, errorCallback = null) => {
  // noinspection JSUnresolvedVariable
  const config = {
    useCdnDomain: true,
    region: qiniu.region.z2
  }
  const putExtra = {
    params: {
      'x:user': this.file
    }
  }
  // noinspection JSUnresolvedFunction
  const observable = qiniu.upload(file, new Date().getTime(), token, putExtra, config)
  observable.subscribe({
    next (res) {
      if (next !== null && typeof next === 'function') {
        next(res)
      }
    },
    error (res) {
      if (errorCallback !== null && typeof errorCallback === 'function') {
        errorCallback(res)
      }
    },
    complete (res) {
      if (successCallback !== null && typeof successCallback === 'function') {
        successCallback(res)
      }
    }
  })
  return observable
}

/**
 * 上传用户头像
 * @param file 头像文件
 * @param successCallback 成功回调
 * @param errorCallback 失败回调
 */
export const uploadFileHeadImage = (file, successCallback = null, errorCallback = null) => {
  obtainUploadTokenHeadImage(file, data => {
    if (data.code === constants.resultCode.OK) {
      uploadFile(file, data.object, successCallback, errorCallback)
    }
  }, error => {
    if (errorCallback !== null && typeof errorCallback === 'function') {
      errorCallback(error)
    }
  })
}

/**
 * 上传商品图片
 * @param file 商品图片文件
 * @param successCallback 成功回调
 * @param errorCallback 失败回调
 */
export const uploadFileGoodsFile = (file, successCallback = null, errorCallback = null) => {
  obtainUploadTokenGoodImage(file, data => {
    if (data.code === constants.resultCode.OK) {
      uploadFile(file, data.object, successCallback, errorCallback)
    }
  }, error => {
    if (errorCallback !== null && typeof errorCallback === 'function') {
      errorCallback(error)
    }
  })
}
